#完成底层的封装，find方法
import yaml
from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException
import logging
from selenium.webdriver.support.wait import WebDriverWait

class BasePage():
    logging.basicConfig(level=logging.INFO)
    _black_list = []
    _error_count = 0
    _error_max = 10
    _params = {}
    _verify_result = ''

    def __init__(self, driver:WebDriver = None):
        self.driver = driver
        logging.info(driver)

    #查找页面元素
    def find(self,_by,locator=None):
        logging.info(_by)
        logging.info(locator)
        #支持解元组的操作和单独读取数据内容
        '''
        try:
            element = self.driver.find_elements(*by) if isinstance(by, tuple) else self.driver.find_element(by, locator)
            self._error_count = 0
            return element
        except Exception as e:
            self._error_count += 1
            for black in self._black_list:
                elements = self.driver.find_element(*black)
                if len(elements) > 0:
                    elements[0].click()
                    return self.find(by, locator)
            raise e
        '''
        #加upper的作用是保证yaml文件里是小写的时候，也能够正常获取
        if _by.upper() == "XPATH":
            by_type = MobileBy.XPATH
        if _by.upper() =="ID":
            by_type = MobileBy.ID
        if _by.upper() =="ANDROID_UIAUTOMATOR":
            by_type = MobileBy.ANDROID_UIAUTOMATOR

        element = self.driver.find_element(by_type, locator)
        WebDriverWait(self.driver, 10).until(lambda x:x.find_element(by_type, locator))

        return element

    def swipe_find(self, text, num=4):
        for i in range(0,num):
            if i == num-1:
                raise NoSuchElementException(f"找了{num-1}没有找到元素")

            try:
                return self.find(MobileBy.XPATH, f"//*[@text={text}]")
            except:
                print("未找到，滑动")
                size = self.driver.get_window_size()
                width = size['width']
                height = size['height']

                startx = width/2
                starty = height * 0.8
                endx = startx
                endy = height * 0.2

                duration = 2000

                self.driver.swipe(startx, starty, endx,endy,duration)

    #返回上一层目录
    def goback(self):
        self.driver.back()

    def steps(self, filename, page_action):
        with open(f"../steps/{filename}", encoding='utf-8') as f:
            steps:list[dict] = yaml.safe_load(f)[f'{page_action}']
            for step in steps:
                print(step)
                print(type(step))
                if "by" in step.keys():
                    element = self.find(step["by"], step['locator'])


                if "action" in step.keys():
                    if "click" == step["action"]:
                        element.click()
                    if "send" == step["action"]:
                        '''
                        1.命中规则：传入的参数为键值对，且已给_params赋值，步骤里文件里的value命中_params的键值来命中
                        2.content_key:获取步骤value的值
                        3.根据content_key匹配_param_list的键值，将获取的参数赋值给content
                        4.将content内容send_keys到对应元素的文本框
                        '''
                        content_key = step["value"]
                        content = self._params[content_key]
                        element.send_keys(content)

                    #如果action为verify，则获取对应元素的内容，并将对应内容赋值给_verify_result
                    if "verify" == step["action"]:
                        self._verify_result = element.get_attribute("text")






